package servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;

import pojo.User;
import utils.db.impl.EditAccount;

/**
 * Servlet implementation class ChangePasswordServlet
 */
@WebServlet("/ChangePasswordServlet")
public class ChangePasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession(true);
		User user=(User)session.getAttribute("user");
		String oldPassword = DigestUtils.md5Hex(request.getParameter("oldPassword"));
		String newPassword = DigestUtils.md5Hex(request.getParameter("newPassword"));
		String confirmPassword = DigestUtils.md5Hex(request.getParameter("confirmPassword"));
		String userPassword = user.getPassword();
		int id = user.getId();
		
		if(oldPassword!="" && newPassword!="" && confirmPassword!=""){
			if(userPassword.equals(oldPassword)){
				if(newPassword.equals(confirmPassword)){
					EditAccount edit = new EditAccount();
					edit.editPassword(id, newPassword);
					user.setPassword(newPassword);
					session.setAttribute("user", user);
					session.setAttribute("warning", "Hasło zostało zmienione!");
					response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
					response.setHeader("Location", "index.jsp?page=userPanel#page");
					
				}else{
					//hasla roznia sie od siebie
					session.setAttribute("warning", "Podane hasła różnią się od siebie!");
					response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
					response.setHeader("Location", "index.jsp?page=userPanel#page");
				}
			}else{
				//bledne stare haslo
				session.setAttribute("warning", "Stare hasło jest błędne!");
				response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
				response.setHeader("Location", "index.jsp?page=userPanel#page");
			}
		}else{
			//puste pola
			session.setAttribute("warning", "Niektóre pola pozostały puste!");
			response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
			response.setHeader("Location", "index.jsp?page=userPanel#page");
		}
	}

}
